﻿class Head extends Unit
{
	//head is a special type of Unit which can take keyboard commands to move it's position
	//movement needs to be synced to update, so keypresses are delayed 
	
	private var my_dir:String = null; // container for current direction of movement increment
	private var my_p_snake:Object = null; //store a pointer to the snake to access body objects via array
	private var my_p_world:Object = null; //store a pointer to the world to access food objects via array
	
	function Head()
	{
		super (Unit);//instanciate the base class.
		//trace ("new Head created"); // debug
		
		// create a listener just for this object 
		
		onKeyDown = function () 
		{
			//trace ("keypress");
   			//overide unit move 
			var keycode:Number = Key.getCode();
			
				//interpret the code for the move unit function
				switch(keycode)
				{
					case 37:
						if (my_dir != "right") // prevent crashing into own tail
						{
							my_dir = "left";
						}
						break;
					case 38:
						if (my_dir != "down")
						{
							my_dir = "up";
						}
						break;
					case 39:
						if (my_dir != "left")
						{
							my_dir = "right";
						}
						break;
					case 40:
						if (my_dir != "up")
						{
							my_dir = "down";
						}
						break;
					case 32:
						my_p_snake.die(); //suicide
						break;
					default:
						//my_p_snake.die(); //debug tool
						break;
				}
		}
		Key.addListener(this);
	} 
	public function move_head_unit(Void):String
	{
		move_unit(my_dir);
		return(my_dir);
	}
	public function check_collision(Void):Void
	{
		//check tail collision:
		var tail_copy:Array = my_p_snake.get_tail_array();
		for (var i:Number = 0; i<tail_copy.length; i++)
		{
			//trace("checking collision for: " + tail_copy[i]);
			if (tail_copy[i].hitTest(this._x + (this._width*0.5),this._y + (this._width*0.5)))//xy location because edges overlap...
			{
				//trace ("crash with tail");//debug collision detection
				my_p_snake.die();
				break;
			}
		}
		//check for food...
		var food_copy:Array = my_p_world.get_food_array();
		for (var i:Number = 0; i<food_copy.length; i++)
		{
			if (food_copy[i].hitTest(this._x+(unit_size*0.5),this._y+(unit_size*0.5)))//xy location = centre because edges overlap...
			{
				//trace ("crash with food");//debug collision detection
				my_p_snake.eat(food_copy[i]);
				break;
			}
		}
	}
}